package com.innovation.ic.cyz.base.service.cyz.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.innovation.ic.cyz.base.model.cyz.Tenant;
import com.innovation.ic.cyz.base.model.cyz.TenantImg;
import com.innovation.ic.cyz.base.pojo.variable.tenant_import.TenantImport;
import com.innovation.ic.cyz.base.pojo.variable.tenant_import.TenantImportData;
import com.innovation.ic.cyz.base.mapper.cyz.TenantMapper;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.service.cyz.ImportTenantService;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.client.WebClient;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 获取原厂数据具体实现类
 */
@Service
@Transactional
public class ImportTenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ImportTenantService {

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 从比一比接口中获取原厂数据
     *
     * @return
     */
    @Override
    public ServiceResult<TenantImport> getTenantsFromB1bApi() {
        List<TenantImportData> tenantImportDataList = new ArrayList<>();

        try {
            String result = WebClient.create().method(HttpMethod.GET)
                    .uri(serviceHelper.getB1bApiConfig().getTenants())
                    .header("Authorization", serviceHelper.getB1bApiConfig().getAuthorization())
                    .header("Connection", "keep-alive")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .header("Accept", "*/*")
                    .header("User-Agent", "PostmanRuntime/7.28.4")
//                .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block(); // Duration.ofSeconds(10)

            JSONObject obj = JSONObject.parseObject(result);

            JSONArray arr = obj.getJSONArray("data");
            String js = JSONObject.toJSONString(arr, SerializerFeature.WriteClassName);
            List<Map<String, Object>> tenantsData = (List<Map<String, Object>>) JSONObject.parseObject(js, List.class);


            for (int i = 0; i < tenantsData.size(); i++) {
                TenantImportData newData = new TenantImportData();

                newData.setTenantsid(((JSONObject) tenantsData.get(i)).getInteger("tenantsid"));
                newData.setMemberid(((JSONObject) tenantsData.get(i)).getInteger("memberid"));
                newData.setAdminid(((JSONObject) tenantsData.get(i)).getInteger("adminid"));
                newData.setName(((JSONObject) tenantsData.get(i)).getString("name"));
                newData.setContact(((JSONObject) tenantsData.get(i)).getString("contact"));
                newData.setEmail(((JSONObject) tenantsData.get(i)).getString("email"));
                newData.setMobile(((JSONObject) tenantsData.get(i)).getString("mobile"));
                newData.setUrl(((JSONObject) tenantsData.get(i)).getString("url"));
                newData.setAddress(((JSONObject) tenantsData.get(i)).getString("address"));
                newData.setBlack(((JSONObject) tenantsData.get(i)).getBoolean("black"));
                newData.setAd(((JSONObject) tenantsData.get(i)).getBoolean("ad"));
                newData.setPassword(((JSONObject) tenantsData.get(i)).getString("password"));
                newData.setPermissions(((JSONObject) tenantsData.get(i)).getInteger("permissions"));
                newData.setBrand(((JSONObject) tenantsData.get(i)).getInteger("brand"));
                newData.setImg(((JSONObject) tenantsData.get(i)).getString("img"));
                newData.setDesc(((JSONObject) tenantsData.get(i)).getString("desc"));
                newData.setPosition(((JSONObject) tenantsData.get(i)).getInteger("position"));
                newData.setCreated_at(((JSONObject) tenantsData.get(i)).getDate("created_at"));
                newData.setUsername(((JSONObject) tenantsData.get(i)).getString("username"));
                newData.setInitials(((JSONObject) tenantsData.get(i)).getString("initials"));
                newData.setShop_name(((JSONObject) tenantsData.get(i)).getString("shop_name"));
                newData.setShop_email(((JSONObject) tenantsData.get(i)).getString("shop_email"));
                newData.setShop_mobile(((JSONObject) tenantsData.get(i)).getString("shop_mobile"));
                newData.setStyle(((JSONObject) tenantsData.get(i)).getInteger("style"));
                newData.setContent(((JSONObject) tenantsData.get(i)).getString("content"));

                List<String> atlasList = new ArrayList<>();
                String atlasStr = ((JSONObject) tenantsData.get(i)).getString("atlas");
                if (atlasStr != null && !atlasStr.isEmpty()) {
                    JSONArray atlasArr = ((JSONObject) tenantsData.get(i)).getJSONArray("atlas");
                    for (int j = 0; j < atlasArr.size(); j++) {
                        atlasList.add((String) atlasArr.get(j));
                    }
                }
                newData.setAtlas(atlasList);

                List<String> companyatlasList = new ArrayList<>();
                String companyatlasStr = ((JSONObject) tenantsData.get(i)).getString("companyatlas");
                if (companyatlasStr != null && !companyatlasStr.isEmpty()) {
                    JSONArray companyatlasArr = ((JSONObject) tenantsData.get(i)).getJSONArray("companyatlas");
                    for (int j = 0; j < companyatlasArr.size(); j++) {
                        companyatlasList.add((String) companyatlasArr.get(j));
                    }
                }
                newData.setCompanyatlas(companyatlasList);

                tenantImportDataList.add(newData);
            }
        } catch (Exception e) {
            ServiceResult<TenantImport> serviceResult = new ServiceResult<TenantImport>();
            serviceResult.setMessage(ServiceResult.SELECT_FAIL);
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage(e.getMessage());
            return serviceResult;
        }

        TenantImport tenantImport = new TenantImport();
        tenantImport.setData(tenantImportDataList);

        ServiceResult<TenantImport> serviceResult = new ServiceResult<TenantImport>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(tenantImport);

        return serviceResult;
    }

    /**
     * 将TenantImport转为Tenant列表
     * @return
     */
    @Override
    public ServiceResult<List<Tenant>> ConvertTenantImportToTenant(TenantImport tenantImport) {
        List<Tenant> tenantList = new ArrayList<>();

        if (tenantImport != null && tenantImport.getData() != null && !tenantImport.getData().isEmpty()) {
            List<TenantImportData> tenantImportDataList = tenantImport.getData();
            for (int i = 0; i < tenantImportDataList.size(); i++) {
                Tenant tenant = new Tenant();
                TenantImportData tenantImportData = tenantImportDataList.get(i);

                tenant.setTenantsid(tenantImportData.getTenantsid());
                tenant.setMemberid(tenantImportData.getMemberid());
                tenant.setAdminid(tenantImportData.getAdminid());
                tenant.setName(tenantImportData.getName());
                tenant.setContact(tenantImportData.getContact());
                tenant.setEmail(tenantImportData.getEmail());
                tenant.setMobile(tenantImportData.getMobile());
                tenant.setShop_name(tenantImportData.getShop_name());
                tenant.setShop_email(tenantImportData.getShop_email());
                tenant.setShop_mobile(tenantImportData.getShop_mobile());
                tenant.setInitials(tenantImportData.getInitials());
                tenant.setUrl(tenantImportData.getUrl());
                tenant.setAddress(tenantImportData.getAddress());
                tenant.setBlack(tenantImportData.getBlack());
                tenant.setAd(tenantImportData.getAd());
                tenant.setUsername(tenantImportData.getUsername());
                tenant.setPassword(tenantImportData.getPassword());
                tenant.setPermissions(tenantImportData.getPermissions());
                tenant.setBrand(tenantImportData.getBrand());
                tenant.setImg(tenantImportData.getImg());
                tenant.setDescription(tenantImportData.getDesc());
                tenant.setPosition(tenantImportData.getPosition());
                tenant.setStyle(tenantImportData.getStyle());
                tenant.setContact(tenantImportData.getContact());

                tenantList.add(tenant);
            }
        }

        ServiceResult<List<Tenant>> serviceResult = new ServiceResult<List<Tenant>>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(tenantList);

        return serviceResult;
    }

    /**
     * 将TenantImport转为TenantImg列表
     * @param tenantImport
     * @return
     */
    @Override
    public ServiceResult<List<TenantImg>> ConvertTenantImportToTenantImg(TenantImport tenantImport) {
        List<TenantImg> tenantImgList = new ArrayList<>();

        if (tenantImport != null && tenantImport.getData() != null && !tenantImport.getData().isEmpty()) {
            List<TenantImportData> tenantImportDataList = tenantImport.getData();
            for (int i = 0; i < tenantImportDataList.size(); i++) {
                TenantImportData tenantImportData = tenantImportDataList.get(i);
                int tenantsid = tenantImportData.getTenantsid();

                List<String> atlasList = tenantImportData.getAtlas();
                for (String atlas : atlasList) {
                    TenantImg tenantImg = new TenantImg();
                    tenantImg.setTenant_img_id(UUID.randomUUID().toString().replace("-", ""));
                    tenantImg.setTenantsid(tenantsid);
                    tenantImg.setType(1);
                    tenantImg.setUrl(atlas);
                    tenantImgList.add(tenantImg);
                }

                List<String> companyatlasList = tenantImportData.getCompanyatlas();
                for (String companyatlas : companyatlasList) {
                    TenantImg tenantImg = new TenantImg();
                    tenantImg.setTenant_img_id(UUID.randomUUID().toString().replace("-", ""));
                    tenantImg.setTenantsid(tenantsid);
                    tenantImg.setType(2);
                    tenantImg.setUrl(companyatlas);
                    tenantImgList.add(tenantImg);
                }
            }
        }

        ServiceResult<List<TenantImg>> serviceResult = new ServiceResult<List<TenantImg>>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(tenantImgList);

        return serviceResult;
    }

    /**
     * 批量插入Tenant对象
     *
     * @return
     */
    @Override
    public ServiceResult<Boolean> saveTenantList(List<Tenant> tenantList, List<TenantImg> tenantImgList) {
        if (tenantList != null && !tenantList.isEmpty()) {
            for (int i = 0; i < tenantList.size(); i++) {
                int tenantsid = tenantList.get(i).getTenantsid();
                Tenant tenant = serviceHelper.getTenantMapper().selectById(tenantsid);
                if (tenant == null) {
                    serviceHelper.getTenantMapper().insert(tenantList.get(i));
                } else {
                    serviceHelper.getTenantMapper().updateById(tenantList.get(i));
                }

                // 重新插入相关图片
                serviceHelper.getTenantImgMapper().deleteTenantImgByTenantsId(tenantsid);

                List<TenantImg> relateTenantImgList = tenantImgList.stream().filter(new Predicate<TenantImg>() {
                    @Override
                    public boolean test(TenantImg tenantImg) {
                        return tenantImg.getTenantsid().equals(tenantsid);
                    }
                }).collect(Collectors.toList());
                if (relateTenantImgList != null && !relateTenantImgList.isEmpty()) {
                    serviceHelper.getTenantImgMapper().insertBatchSomeColumn(relateTenantImgList);
                }
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);

        return serviceResult;
    }
}
